package com.quanyue.music.file.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import com.quanyue.auto.cache.CacheService;
import com.quanyue.auto.fs.FsProperties;
import com.quanyue.auto.fs.QiniuServiceImpl;
import com.quanyue.auto.miniapp.support.MiniAppContext;
import com.quanyue.auto.util.AssertUtils;
import com.quanyue.auto.util.KeyGenerator;
import com.quanyue.music.domain.constant.CacheConstants;
import com.quanyue.music.domain.entity.QrCode;
import com.quanyue.music.file.mapper.QrCodeMapper;
import com.quanyue.music.file.service.QrCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class QrCodeServiceImpl implements QrCodeService {
    @Autowired
    private QrCodeMapper qrCodeMapper;
    @Autowired
    private WxMaQrcodeService wxMaQrcodeService;
    @Autowired
    private CacheService cacheService;


    @Override
    public void createCode(String path) {
        try {
            QiniuServiceImpl impl = new QiniuServiceImpl();
            MiniAppContext.setMerchantNo(10100);
            File f = wxMaQrcodeService.createQrcode(path, 430);
            FileInputStream inputStream = new FileInputStream(f);
            MultipartFile file = new MockMultipartFile(f.getName(), inputStream);
            String fileName = file.getName();
            FsProperties properties = cacheService.get(CacheConstants.FS_PROPERTIES_CONFIG.name());
            String url = impl.saveFile(file.getBytes(), KeyGenerator.uuid() + fileName.substring(fileName.lastIndexOf(".")), properties);
            inputStream.close();
            QrCode qrCode = new QrCode();
            qrCode.setPath(path);
            qrCode.setQrCode(url);
            qrCode.setCreateTime(LocalDateTime.now());
            qrCodeMapper.insert(qrCode);
        } catch (Exception e) {
            throw new AssertUtils.ValidateException(e.getMessage());
        }
    }

    @Override
    public List <QrCode> selectCode() {
        return qrCodeMapper.findAll();
    }

    @Override
    public void deleteCode(String id) {
        qrCodeMapper.deleteOne(id);
    }
}
